import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

public class ClientServer {
	public static void main(String[] args) throws IOException {
//		httpClient();		
		httpServer();
	}
	
	private static void httpClient() throws UnknownHostException, IOException {
		Socket s = new Socket("ya.ru", 80);
		
		OutputStream out = s.getOutputStream();
		
		out.write(("GET / HTTP/1.1\r\nHost: ya.ru\r\n\r\n").getBytes());
		
		InputStream in = s.getInputStream();
		
		InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
		
		BufferedReader bReader = new BufferedReader(reader);
						
		String line;
		
		int count = 0;
		
		while((line = bReader.readLine()) != null) {
			System.out.println(line);
			
			if (line.isEmpty()) count++;
			
			if (count == 2) break;
		}
		
		s.close();
	}

	private static void httpServer() throws IOException {
		ServerSocket ss = new ServerSocket(5678);
		
		Socket s = ss.accept();
		
		InputStream in = s.getInputStream();
		
		InputStreamReader reader = new InputStreamReader(in);
		
		BufferedReader bReader = new BufferedReader(reader);
						
		String line;
		
		while((line = bReader.readLine()) != null) {
			System.out.println(line);
			
			if (line.isEmpty()) {
				break;				
			}
		}
		
		String response = "HTTP/1.1 200 Ok\n" +				     	  				     	  
				          "Content-Type: text/html; charset=UTF-8\n" + 
				          "Connection: close\n\n"+								
				          "Hello!\n\n";
		
		s.getOutputStream().write(response.getBytes());
		
		s.close();
	}
}
